package com.yxy.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yxy.common.PageResult;
import com.yxy.constant.MessageConstant;
import com.yxy.constant.StatusConstant;
import com.yxy.context.BaseContext;
import com.yxy.exception.BannerTitleAlreadyExistsException;
import com.yxy.mapper.BannerMapper;
import com.yxy.pojo.dto.BannerDTO;
import com.yxy.pojo.dto.BannerPageQueryDTO;
import com.yxy.pojo.entity.Banner;
import com.yxy.pojo.vo.BannerPageQueryVO;
import com.yxy.pojo.vo.BannerVO;
import com.yxy.service.BannerService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class BannerServiceImpl implements BannerService {

    @Autowired
    private BannerMapper bannerMapper;

    /**
     * 分页查询
     * @param bannerPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(BannerPageQueryDTO bannerPageQueryDTO) {
        PageHelper.startPage(bannerPageQueryDTO.getPage(), bannerPageQueryDTO.getPageSize());
        Page<BannerPageQueryVO> page = bannerMapper.pageQuery(bannerPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 新增
     * @param bannerDTO
     */
    @Override
    public void add(BannerDTO bannerDTO) {
        // 判断标题是否存在
        Banner b = bannerMapper.selectByTitle(bannerDTO.getTitle());
        if (b != null) {
            throw new BannerTitleAlreadyExistsException(MessageConstant.BANNER_ALREADY_EXISTS);
        }
        Banner banner = new Banner();
        BeanUtils.copyProperties(bannerDTO, banner);
        banner.setCreateTime(LocalDateTime.now());
        banner.setCreateUser(BaseContext.getCurrentId());
        banner.setStatus(StatusConstant.ENABLE);
        bannerMapper.insert(banner);
    }

    /**
     * 修改
     * @param id
     * @param status
     */
    @Override
    public void updateStatus(int id, int status) {
        bannerMapper.updateStatus(id, status);
    }

    /**
     * 批量删除
     * @param ids
     */
    @Override
    public void batchDelete(int[] ids) {
        bannerMapper.deleteByIds(ids);
    }

    /**
     * 获取轮播图列表
     * @return
     */
    @Override
    public List<BannerVO> getBannerList() {
        return bannerMapper.getAll();
    }
}
